#!/usr/bin/env python
#coding=utf-8
'''
Created on Jul 22, 2010

@author: lxd
'''
import wx
import common.feedparser as feedparser
import threading
import datetime
import os
import re

class GetRssThread(threading.Thread):        
    def __init__(self, window, rss):
        threading.Thread.__init__(self)
        self.timeToQuit = threading.Event()
        self.timeToQuit.clear()
        self.window = window
        self.rss = rss
        
    def stop(self):
        self.timeToQuit.set()
          
    def run(self):
        for r in self.rss:            
            d = feedparser.parse(r['url'])
            wx.CallAfter(self.window.getRssCall, d, r)
#            print r['name']   
            
def cleanBLog(data):
    #清除html标签
    data = re.sub(r'</p>', '\n', data)#加上分段
    data = re.sub(r'\&[a-zA-Z]{1,10};', '', data)#过滤&lt;
    data = re.sub(r'<[^>]*>', '', data)#过滤<>
    data = re.sub(r'[(/>)<]', '', data)#过滤单独的<>   
    return data
        
class MainFrame(wx.Frame):
    def __init__(self, rss):
        wx.Frame.__init__(self, None, -1, title=u'日志查看', style=wx.DEFAULT_FRAME_STYLE)
        self.palMain = wx.Panel(self)      
        self.LstrlContent = self.createLstrlContent()
        self.layout()   
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelect, self.LstrlContent)
             
        self.fetchRss(rss)   
        self.Center()

    def fetchRss(self, rss):
        self.today = str(datetime.datetime.date(datetime.datetime.now()))
        if not os.path.exists(self.today):
            os.mkdir(self.today)
        else:
            retCode = wx.MessageBox(u'今天的日志内容已存在，点击“确定”重新获取，点击“取消”显示已存在的内容', u'友情提示', style=wx.YES_NO | wx.ICON_QUESTION)
            if (retCode == wx.YES):
                GetRssThread(self, rss).start()
            else:
                self.getLocalRss()
             
    def createLstrlContent(self):
        lstrlContent = wx.ListCtrl(self.palMain, -1, size=(550, 500), style=wx.LC_REPORT | wx.LC_VRULES | wx.LC_HRULES)
        lstrlContent.InsertColumn(0, u"来源")
        lstrlContent.InsertColumn(1, u"名称")
        lstrlContent.SetColumnWidth(0, 150)
        lstrlContent.SetColumnWidth(1, 400)
        return lstrlContent
   
    def layout(self):
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(self.LstrlContent, 1, wx.ALL | wx.EXPAND, 5)
        self.palMain.SetSizer(mainSizer)
        mainSizer.Fit(self)
        mainSizer.SetSizeHints(self)  
        
    def getRssCall(self, d, rss):
        if d.entries:
            filedir = '%s/%s' % (self.today, rss['name'])
            if not os.path.exists(filedir):
                os.mkdir(filedir)              
            
            for entry in d.entries:           
                f = open(ur'%s/%s/%s.txt' % (self.today, rss['name'], entry.title), 'w')
                blog = cleanBLog(entry.summary)
                f.write(blog)
                f.close()            

                index = self.LstrlContent.InsertStringItem(0, rss['name'])
                self.LstrlContent.SetStringItem(index, 1, entry.title)  
        else:
            wx.MessageBox(u'%s(%s)不是可用的RSS源，请删除' % (rss['name'], rss['url']), u'友情提示', style=wx.OK | wx.ICON_EXCLAMATION)
#            print '%s(%s)不是可用的RSS源，请删除' % (rss['name'], rss['url']) 

    def getLocalRss(self):
        for root, dirs, files in os.walk(self.today):
            for file in files:
                name = root[root.find('/') + 1:]
                title = file[:file.rfind('.')]
                index = self.LstrlContent.InsertStringItem(0, name)
                self.LstrlContent.SetStringItem(index, 1, title) 
                
#                self.LstrlContent.SetStringItem(index, 1, name) 
#                self.LstrlContent.SetStringItem(index, 1, title)  
#                print file[:file.rfind('.')]

    def OnItemSelect(self, event):
        index = event.GetIndex()
        name = self.LstrlContent.GetItem(index, 0).Text
        title = self.LstrlContent.GetItem(index, 1).Text
        f = open(ur'%s/%s/%s.txt' % (self.today, name, title), 'r')
        blog = f.read()
        f.close()   
        wx.MessageBox(u'%s' % blog, u'友情提示', style=wx.OK | wx.ICON_EXCLAMATION)

if __name__ == "__main__":
    app = wx.App()
    MainFrame().Show()
    app.MainLoop()


